#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash ldc2-1.15.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

set -e
yum install -y wget tar environment-modules  

if `wget -t 40 -c -P $buildpath  https://ghproxy.com/https://github.com/ldc-developers/ldc/releases/download/v1.15.0-beta2/ldc2-1.15.0-beta2-linux-aarch64.tar.xz`
then 
   echo "ldc2-1.15.0-beta2-linux-aarch64.tar.xz下载成功!(国内github加速下载)"
elif `wget -t 40 -c -P $buildpath  https://github.com/ldc-developers/ldc/releases/download/v1.15.0-beta2/ldc2-1.15.0-beta2-linux-aarch64.tar.xz`
then 
   echo "ldc2-1.15.0-beta2-linux-aarch64.tar.xz下载成功!"
else
   echo "ldc2-1.15.0-beta2-linux-aarch64.tar.xz下载失败!"
fi
tar xf $buildpath/ldc2-1.15.0-beta2-linux-aarch64.tar.xz -C $buildpath && rm -rf $buildpath/ldc2-1.15.0-beta2-linux-aarch64.tar.xz
mkdir -p $installpath/ldc2-1.15.0  && cp  -r $buildpath/ldc2-1.15.0-beta2-linux-aarch64/* $installpath/ldc2-1.15.0

cat>"$installpath/ldc2-1.15.0/ldc2_modulefiles"<<EOF
#%Module1.0
conflict ldc2
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set LDC2 \$pwd
setenv LDC2 \$LDC2
prepend-path PATH \$LDC2/bin
prepend-path LIBRARY_PATH \$LDC2/lib
EOF

rm -rf $buildpath/ldc2-1.15.0-beta2-linux-aarch64
